package edu.sctu.yueding.utils;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import edu.sctu.yueding.R;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.VersionBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;

/**
 * Created by fll on 2016/8/2.
 */
public class UpdateManager {

    private ProgressBar mProgressBar;
    private Dialog mDownloadDialog, mIsUpdateDialog;

    private SharePreference sharePreferce;

    private String mSavePath;
    private int mProgress;

    private boolean mIsCancel = false;

    private static final int DOWNLOADING = 1;
    private static final int DOWNLOAD_FINISH = 2;

    private String mVersion_code;
    private String mVersion_name;
    private String mVersion_desc;
    private String mVersion_path;
    private long size = -1;
    int localVersion;
    private String apkName = "yuding.apk";


    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};

    private Context mContext;
    private Activity mActivity;


    @TargetApi(Build.VERSION_CODES.M)
    public UpdateManager(Context context) {
        mContext = context;
    }


    private Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    mProgressBar.setProgress(mProgress);
                    //设置进度条
                    break;
                case DOWNLOAD_FINISH:
                    //隐藏当前下载对话框
                    //安装APK文件
                    mDownloadDialog.dismiss();
                    installAPK();
                    break;
            }
        }
    };

    /**
     * 检查软件是否更新的入口
     */

    public void checkUpdate() {

        Response.Listener<String> listener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                L.d("update", json);
                try {
                    JsonBaseBeen<VersionBean> versionBean = JSON.parseObject(json, new TypeReference<JsonBaseBeen<VersionBean>>() {
                    }.getType());
                    mVersion_code = String.valueOf(versionBean.getData().getVersionCode());
                    mVersion_name = versionBean.getData().getName();
                    mVersion_desc = versionBean.getData().getDescription();
                    mVersion_path = versionBean.getData().getUrl();

                    SharePreference.getInstance(mContext).setCache(CacheConfig.CACHE_LOCAL_VERSION, mVersion_code + "");

                    size = versionBean.getData().getSize();

                    if (isUpdate()) {
                        Toast.makeText(mContext, "需要更新", Toast.LENGTH_SHORT).show();
                        showNoticeDialog();
                    } else {
//                    Toast.makeText(mContext, "已经是最新", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception exception) {
                    exception.printStackTrace();
                    Toast.makeText(mContext, "版本更新错误", Toast.LENGTH_LONG).show();
                }

            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                L.d("update", "error");
            }
        };

        GetVolleyHttp.getInstance((Activity) mContext).getStringGETJsonData(URLConfig.APP_UPDATE,
                listener, errorListener, (long) 500);

    }

    /**
     * 将服务器版本与本地版本比较并判断是否需要更新
     */

    protected boolean isUpdate() {
        String serverVersion = mVersion_code;

        Float fServerVersion = Float.parseFloat(serverVersion);


        try {
            localVersion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        System.out.print(localVersion + serverVersion);


        Log.e("local", "" + localVersion);
        if (fServerVersion > localVersion)
            return true;
        else
            return false;
    }

    /**
     * 如果需要更新，显示提示更新的提示框
     */
    public void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        String message = "软件有更新，需要下载安装吗？\n"
                + "最新版本号：" + mVersion_code + "\n"
                + "当前版本号：" + localVersion;
        builder.setMessage(message);

        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {


                dialog.dismiss();
                showDownloadDialog();
            }
        });

        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //隐藏当前对话框

                sharePreferce = SharePreference.getInstance(mContext);
                sharePreferce.setCache(CacheConfig.CACHE_IS_CLICK_UPDATE_CANCEL, true);

                dialog.dismiss();
            }
        });
        mIsUpdateDialog = builder.create();
        mIsUpdateDialog.setCanceledOnTouchOutside(false);
        mIsUpdateDialog.show();
    }

    /**
     * 点击确认更新后，显示正在下载的提示框
     */

    protected void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("下载中");
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_progress, null);

        mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
        builder.setView(view);

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //隐藏当前对话框
                dialog.dismiss();
                mIsCancel = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.setCanceledOnTouchOutside(false);
        mDownloadDialog.show();

        //下载文件
        downloadAPK();
    }

    /**
     * 开启新的线程来下载文件
     */
    protected void downloadAPK() {
        new Thread(new Runnable() {
            @Override
            public void run() {

//                // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//
//                    // 检查该权限是否已经获取
//                    int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
//                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//                    if (i != PackageManager.PERMISSION_GRANTED) {
//                        // 如果没有授予该权限，就去提示用户请求
//
////                        PermissionUtil.showDialogTipUserRequestPermission(mActivity, permissions);
//                        ActivityCompat.requestPermissions(mActivity, permissions, 321);
//
//                    } else {
//                        JumpUtils.isLoginJump(getActivity(), UploadNewsActivity.class);
//                    }
//
//                } else {
//                    JumpUtils.isLoginJump(getActivity(), UploadNewsActivity.class);
//                }

                try {
                    // 判断SD卡是否存在，并且是否具有读写权限
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        // 获得存储卡的路径
                        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                        mSavePath = sdPath + "/悦定";
                        apkName = mVersion_name + ".apk";

                        File dir = new File(mSavePath);
                        // 判断文件目录是否存在
                        if (!dir.exists())
                            dir.mkdir();
                        //下载文件
                        HttpURLConnection connection = (HttpURLConnection) new URL(mVersion_path).openConnection();
                        connection.connect();

                        InputStream is = connection.getInputStream();
                        int length = connection.getContentLength();

                        if (length != -1) {
                            size = length;
                        }

                        File apkFile = new File(mSavePath, apkName);
                        FileOutputStream fos = new FileOutputStream(apkFile);

                        int count = 0;
                        // 缓存
                        byte[] buffer = new byte[1024];
                        while (!mIsCancel) {
                            int numberread = is.read(buffer);
                            count += numberread;
                            //计算进度条的当前位置；
                            mProgress = (int) (((float) count / size) * 100);
                            mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);
                            // 下载完成
                            if (numberread < 0) {
                                mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                                break;
                            }
                            // 写入文件
                            fos.write(buffer, 0, numberread);
                        }
                        fos.close();
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 将下载后的文件安装在本地
     */

    protected void installAPK() {
        File file = new File(mSavePath, apkName);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        intent.setDataAndType(Uri.fromFile(file), type);
        mContext.startActivity(intent);
    }
}

